﻿using System.Linq;
using System.Windows;
using VsxFactory.Modeling.Repository;
using System;
using VsxFactory.Modeling.Strategies;
using VsxFactory.Modeling.StrategyManager.Strategies;
using Microsoft.VisualStudio.ExtensionsExplorer;

namespace VsxFactory.Modeling.StrategyManager.Dialog.Providers
{
    /// <summary>
    /// IVsExtensionsProvider implementation responsible for gathering
    /// a list of installed packages which will be shown in the Add Package dialog.
    /// </summary>
    internal class InstalledPackagesProvider : PackagesProviderBase
    {

        public InstalledPackagesProvider(VisualStudioStrategyContext context, ResourceDictionary resources)
            : base(context, resources) {
        }

        public override float SortOrder {
            get {
                return 1.0f;
            }
        }

        public override string Name {
            get {
                return "Local";
            }
        }

        public override bool RefreshOnNodeSelection {
            get {
                return true;
            }
        }

        protected override void FillRootNodes() {
            var allNode = new SimpleTreeNode(this, "All", RootNode, Context.LocalRepository);

            RootNode.Nodes.Add(allNode);
        }

        public override bool CanExecute(PackageItem item) {
            // enable command on a Package in the Installed provider if the package is installed.
            return !Context.SolutionRepository.GetPackages().Any(p => p.ID == item.PackageIdentity.ID && p.Version == item.Version);
        }

        protected override bool ExecuteCore(PackageItem item) {
            // On le télécharge
            Context.LocalRepository.InstallPackage(item.PackageIdentity);
            // Et on l'active dans la solution
            Context.SolutionRepository.InstallPackage(item.PackageIdentity);
            return true;
        }

        protected override void OnExecuteCompleted(PackageItem item) {
            if (SelectedNode != null) {
                SelectedNode.Extensions.Remove((IVsExtension)item);
            }
        }

        public override IVsExtension CreateExtension(PackageInfo package) {
            return new PackageItem(this, package, null) {
                CommandName = "Enable"
            };
        }

        public override string NoItemsMessage {
            get {
                return Resources.Dialog_InstalledProviderNoItem;
            }
        }

        public override string ProgressWindowTitle {
            get {
                return Resources.Dialog_UninstallProgress;
            }
        }

        protected override string GetProgressMessage(PackageInfo package) {
            return Resources.Dialog_UninstallProgress + package.ToString();
        }
    }
}
